#pragma once
#include <iostream>
#include <string>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <cstring>

namespace client
{
    using namespace std;
    class udpClient
    {
    public:
        udpClient(const string serverip, uint16_t serverport)
            : _serverip(serverip), _serverport(serverport), _quit(false), _sockfd(-1)
        {
        }

        void init()
        {
            // 创建socket
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                std::cerr << "create sockfd fail!" << std::endl;
                exit(2);
            }
            cout << "sockfd success" << _sockfd << endl;
            // 客服端需要bind吗？  不需要 bind是我们需要确定端口一直不改变 我们只需要知道服务器端口就可以，客户端端口可以由
            // 操作系统来自己决定
            // client 需不需要创建bind[必须创建bind] client需不需要明确也即我们去操作绑定bind[不需要]
        }

        static void *read_sock(void *args)
        {
            int _sockfd = *(static_cast<int *>(args));
            pthread_detach(pthread_self());
            while (true)
            {
                char line[1024];
                struct sockaddr_in nothing;
                socklen_t len = sizeof(nothing);

                size_t n = recvfrom(_sockfd, line, sizeof(line) - 1 , 0, (struct sockaddr *)&nothing, &len);
                if (n > 0)
                {
                    line[n] = 0;
                }
                cout << line << endl;
            }
        }

        void run()
        {
            pthread_create(&readthread, nullptr, read_sock, (void *)&_sockfd);
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));

            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            string str;
            char message[1024];
            while (!_quit)
            {
                fprintf(stderr,"Enter #");
                fflush(stderr);
                // cin >> message;
                fgets(message, sizeof(message), stdin);
                message[strlen(message)-1] = 0;
                // 需要告诉网络去哪里找
                str = message;
                sendto(_sockfd, str.c_str(), str.size(), 0, (struct sockaddr*)&server, sizeof(server));
            }
        }
        ~udpClient()
        {
        }

    private:
        int _sockfd;
        uint16_t _serverport;
        string _serverip;
        bool _quit;

        pthread_t readthread;
    };

}